<template>
    <!-- Main content -->
    <div>
        <div class="row">
            <div class="col-xs-12">
                <theme-box title="商户押金流水">
                    <form class="form-inline" @submit.prevent v-el:form>
                        <form-select title="商户名称"  :up-table="true" name="mchtId" :options="mchtList" :value.sync ="mchtIdValue"></form-select>
                        <div class="form-group" style="margin-bottom: 17px">
                            <label class="control_up_label">电子券名称：</label>
                            <select name="couponName" class="form-control" style="width: 265px;min-width: 265px">
                                <option value="" checked="checked">所有电子券</option>
                                <option v-for="mcht in coupList" :value="mcht.key">
                                    {{mcht.key}}
                                </option>
                            </select>
                        </div>
                        <!--<form-select title="电子券名称" :sreach="true" :up-table="true" name="couponId" :options="coupList"></form-select>-->
                        <form-select title="状态" :up-table="true" name="state" :options="statTpe"></form-select>
                        <form-date-time title="开始时间" :up-table="true" name="startDate"></form-date-time>
                        <form-date-time title="结束时间" :up-table="true" name="endDate"></form-date-time>

                        <button type="reset" @click="reset" class="btn btn-warning pull-right">重置</button>
                        <v-button theme="primary" @click="search" class="pull-right">查询</v-button>
                    </form>
                    <table class="table table-bordered table-striped" style="width:100%" v-el:table>
                    </table>
                </theme-box>
            </div>
            <!-- /.col -->
        </div>
        <modal-container title="编辑" v-el:modal v-ref:modal class="edit-modal">
            <form @submit.prevent @reset.prevent v-el:mform>
                <div class="modal-body">
                    <table-modal :item="item" :columns-set="columnsSet"></table-modal>
                </div>

                <div class="modal-footer">
                    <v-button class="pull--left" data-dismiss="modal" @click="resetBindDrag">关闭</v-button>
                    <v-button theme="primary" type="submit">保存</v-button>
                </div>
            </form>
        </modal-container>
        <modal-container title="补押" v-el:add-modal v-ref:add-modal class="edit-modal">
            <form @submit.prevent @reset.prevent v-el:add-mform>
                <div class="modal-body">
                    <table-modal :item="item" :columns-set="columnsAddSet"></table-modal>
                </div>

                <div class="modal-footer">
                    <v-button class="pull--left" data-dismiss="modal" @click="resetBindDrag">关闭</v-button>
                    <v-button theme="primary" type="submit">保存</v-button>
                </div>
            </form>
        </modal-container>
        <!-- /.row -->
    </div>
    <!-- /.content -->
</template>

<style lang="less" scoped>
    .form-inline .btn+.btn {
        margin-right: 10px;
        margin-top:3px;
    }

    .btn{
        margin-top:3px;
    }
</style>
<script>
    //解决datatables弹窗警告
    $.fn.dataTable.ext.errMode = 'none';
    import {
        dateTime,
        createDataTable
    } from 'ui/collections/general.js'
    var serialize = require('form-serialize');
    import {dateTransform} from "lib/method.js"

    var dataTable;
    var columnsSet;
    export default {
        data: () => ({
            mchtIdValue:'',
            mchtList:[],
            coupList:[],
            item: {},
            columnsSet: [],
            columnsAddSet: [{
                title: "商户号",
                data: "mchtId",
                edit: true,
                readonly:true,
                className: "operate"
            }, {
                title: "商户名称",
                data: "mchtName",
                edit: true,
                readonly:true,
                className: "operate"
            }, {
                title: "电子券号",
                data: "couponId",
                edit: true,
                readonly:true,
                className: "operate"
            }, {
                title: "电子券名称",
                data: "couponName",
                edit: true,
                readonly:true,
                className: "operate"
            }, {
                title: "金额",
                data: "supplement",
                edit: true,
                className: "operate"
            },{
                title: "有效结束日期",
                data: "validatyEnd",
                edit:true,
                readonly:true,
                className: "operate"
            }],
            statTpe:[
                {key:"所有状态",value:""},
                {key:"待使用",value:"0"},
                {key:"已结清",value:"1"},
                {key:"使用中",value:"2"},
                {key:"待退款",value:"3"}
            ]
        }),
        watch:{
            async mchtIdValue(v){
                if(v != ''){
                    await this.$post({
                        url: "/api/v2" + projectName_Url + "/plat/coupon/queryCoupon",
                        data:{mchtId:v},
                        method:"POST"
                    }).then(response => {
                        let list = response.content.list;
                        if(list != '' && list != null){
                            this.$set("coupList", list);
                        }else{
                            this.coupList = []
                        }
                    }, error => {});
                }else{
//                    this.coupList = []
                    await this.$post({
                        url: "/api/v2" + projectName_Url + "/plat/coupon/queryCoupon",
                        data:{mchtId:""},
                        method:"POST"
                    }).then(response => {
                        let list = response.content.list;
                        if(list != '' && list != null){
                            list.unshift({key:"所有电子券",value:""});
                            this.$set("coupList", list);
                        }
                    }, error => {});
                }
            }
        },
        methods: {
            //还原弹出框位置
            resetBindDrag() {
                this.$refs.modal._resetBindDrag();
            },
            //查询按钮
            search: function() {
                dataTable.ajax.reload();
            },
            //重置按钮
            reset: function() {
                this.getCoupon();
                $(".form-inline")[0].reset();
                dataTable.ajax.reload();
            },
            getMcht() {
                let self = this;
                var mchtId = JSON.parse(localStorage.getItem("id_token")).mchtId
                self.$post({
                    url: '/api/v2' + projectName_Url + '/list/mcht/' + mchtId,
                    method: "GET"
                }).then(response => {
                    let list = response.content.info;
                    if(list != '' && list != [] && list != null){
                        if(list.length > 1){
                            list.unshift({key:"所有商户",value:""});
                            self.$set("mchtList", list);
//                        self.mchtIdValue = list[0].value
                        }else{
                            self.$set("mchtList", list);
                        }
                    }
                },  error => {});
            },
            getCoupon(){
                let self = this;
                self.$post({
                    url: '/api/v2' + projectName_Url + '/plat/coupon/queryCoupon',
                    data:{mchtId:''},
                    method: "POST"
                }).then(response => {
                    let list = response.content.list;
                    if(list != '' && list != null){
                        list.unshift({key:"所有电子券",value:""});
                        this.$set("coupList", list);
                    }
                },  error => {});
            }

        },
        created() {
            //datatable所用数组
            columnsSet = [{
                title: "商户号",
                data: "mchtId",
                edit: true,
                readonly:true,
                className: "operate"
            }, {
                title: "商户名称",
                data: "mchtName",
                edit: true,
                readonly:true,
                className: "operate"
            }, {
                title: "电子券号",
                data: "couponId",
                edit: true,
                readonly:true,
                className: "operate",


            }, {
                title: "电子券名称",
                data: "couponName",
                edit: true,
                readonly:true,
                className: "operate",
            },{
                title: "电子券数量",
                data: "couponNum",
                edit: true,
                readonly:true,
                className: "operate",
            },{
                title: "押金金额",
                data: "depoAmt",
                edit: true,
                readonly:true,
                className: "operate",
            },{
                title: "已使用金额",
                data: "useAmt",
                edit: true,
                readonly:true,
                className: "operate",
            },{
                title: "押金类型",
                data: "depositType",
                className: "operate",
                render: function (data) {
                    var value;
                    if(data == "market"){
                        value = '营销'
                    }else if(data == 'sett'){
                        value = '结算'
                    }else{
                        value = data
                    }
                    return value;
                }
            }, {
                title: "状态",
                data: "state",
                className: "operate",
                render: function (data) {
                    var value;
                    if(data == "0"){
                        value = '待使用'
                    }else if(data == '1'){
                        value = '已结清'
                    }else if(data == '2'){
                        value = '使用中'
                    }else{
                        value = '待退款'
                    }
                    return value;
                }
            }, {
                title: "有效结束日期",
                data: "validatyEnd",
                className: "operate",
                render:function(data){
                    return dateTransform(data)
                }
            },
                {
                    title: "押金日期",
                    data: "createDate",
                    className: "operate",
                    render:function(data){
                        return dateTransform(data)
                    }
                },
                {
                    title: "相关操作",
                    className: "operate",
                    width: "160px",
                    render: function(value, type, row) {
                        if (row.state == "0" && row.expired == "true") {
                            return `
                           <button type="button" class="btn btn-primary btn-sm edit">退回</button>
                      `
                       }else if(row.state == "3"){
                            return `
                           <button type="button" class="btn btn-primary btn-sm edit">退回</button>
                      `
                      }else if(row.depositType == 'sett' && row.supplement > 0 ){
                            return `
                      <button type="button" class="btn btn-primary btn-sm add">补押</button>
                      `
                      }
                    }
                }]
        },
        ready: async function() {
            dateTime({
                format: "yyyy-mm-dd",
                minView: "2",
                startDate: "",
                endDate: ""
            })
            this.$set("columnsSet", columnsSet)
            var self = this;
            self.getMcht();
            self.getCoupon();
            //创建dataTable
            dataTable = $(this.$els.table).DataTable({
                "columns": this.columnsSet, //定义列
                "ajax": async function(data, callback, settings) {
                    var page = [{
                        "name": "iDisplayStart",
                        "value": 1 + data.start / data.length
                    }, {
                        "name": "iDisplayLength",
                        "value": data.length
                    }];
                    //表单序列化数据
                    var _data = serialize(self.$els.form, {
                        hash: true,
                        disabled: true,
                        empty: true
                    });
                    _data.aoData = JSON.stringify(page);
                    //对开始日期进行数据处理
                    _data.startDate = _data.startDate.replace(/-/g, "");
                    _data.endDate = _data.endDate.replace(/-/g, "");
                    //判断日期
                    if(_data.startDate.length>0 && _data.endDate.length>0){
                        if(_data.startDate-_data.endDate > 0){
                            Midway.alert({title: "操作提示", content: '押金开始日期不能大于押金结束日期'})
                            // return false
                        }
                    }else if(_data.startDate.length>0 && _data.endDate.length <=0){
                        Midway.alert({title: "操作提示", content: '押金结束日期不能为空'})
                        // return false
                    }else if(_data.startDate.length <= 0 && _data.endDate.length > 0){
                        Midway.alert({title: "操作提示", content: '押金开始日期不能为空'})
                        // return false
                    }
                    //发送请求
                    var mchtId = JSON.parse(localStorage.getItem("id_token")).mchtId;
                    _data.loginMchtId = mchtId;
                    if(mchtId != '10000000'){
                        _data.mchtId = JSON.parse(localStorage.getItem("id_token")).mchtId;
                    }else{
                        _data.mchtId = _data.mchtId;
                    }
                    var result = await self.$post({
                        url: "/api/v1" + projectName_Url + "/plat/mchtDeposit/query",
                        data:_data,
                        method: "POST"
                    })
                    if (result.respCode != "00") {
                        Midway.alert({
                            title: "操作失败",
                            content: result.content
                        })
                    }
                    callback({
                        recordsTotal: result.content.total,
                        recordsFiltered: result.content.total,
                        data: result.content.mchtDepositMap || []
                    })
                }
            });


            $(self.$el).on("click", ".edit", function() {
                var Row = $(this).closest('tr').get(0);
                const dataArray = JSON.parse(JSON.stringify(dataTable.row(Row).data()));
                self.item = dataArray;
                dateTime()
                //编辑框验证、保存、提交
                $(self.$els.mform).validate(self.item.valdate = {
                    async submitHandler() {
                        var form = self.$els.mform;
                        var _data = serialize(form, { hash: true, disabled:true, empty:true });
                        // return flase
                        _data.depositType = self.item.depositType;
                        var result = await self.$post({
                            url: "/api/v1" + projectName_Url + "/plat/mchtDeposit/backDepositForCommon",
                            data: _data,
                            method: "post"
                        });
                        Midway.alert({title:"操作提示",content:result.errorInfo})

                        dataTable.ajax.reload(null, false);
                        $(self.$els.modal).modal('hide');
                        self.resetBindDrag()
                    },
                    rules: {

                    }
                });
                $(self.$els.modal).modal('show');
            });
          $(self.$el).on("click", ".add", async function() {
            var Row = $(this).closest('tr').get(0);
            const dataArray = JSON.parse(JSON.stringify(dataTable.row(Row).data()));
            self.item = dataArray;
            self.item.timeEnd = dataArray.validatyEnd;
            self.item.validatyEnd = dateTransform(dataArray.validatyEnd);
              //请求剩余押金金额
              self.$post({
                  url: "/api/v1" + projectName_Url + "/plat/mchtDeposit/getSupplement",
                  data:{'mchtId':self.item.mchtId,'couponId':self.item.couponId},
                  method: "POST"
              }).then(response => {
                  var amt = response.content.amt;
                  $("input[name = 'supplement']").val(amt);
              });
            $(self.$els.addMform).validate(self.item.valdate = {
                async submitHandler() {
                    var form = self.$els.addMform;
                    var _data = serialize(form, { hash: true, disabled:true, empty:true });
                    // return flase
                   _data.validatyEnd = self.item.timeEnd;
                    var result = await self.$post({
                        url: "/api/v1" + projectName_Url + "/plat/mchtDeposit/supplementDepoAmt",
                        data:_data,
                        method: "POST"
                    });
                    Midway.alert({title:"操作提示",content:result.errorInfo})

                    dataTable.ajax.reload(null, false);
                    $(self.$els.addModal).modal('hide');
                    self.resetBindDrag()
                },
                rules: {
                    supplement:{
                        required:true,
                        int:true
                    }
                }
            });
            $(self.$els.addModal).modal('show');
         })
        },
        beforeDestroy() {
            $(this.$el).off("click")
        }
    }
</script>
